package com.ys168.gam.searcher;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys168.gam.bean.EngineInfo;
import com.ys168.gam.bean.SearchConditionInfo;

/**
 * 百度搜索
 * 
 * @author Jason Krebs
 * @since 2015年6月9日
 */
public class BaiduSearcher extends BaseSearcher {

    public BaiduSearcher(EngineInfo engineInfo, SearchConditionInfo searchConditionInfo) {
        super(engineInfo, searchConditionInfo);
    }

    @Override
    protected void initConnectionParameter(URLConnection connection) {
        connection.setRequestProperty("Cookie", "BAIDUID=EAAB2CC610BEEAB039E03726E6CF549B:FG=1");
    }

    @Override
    protected List<URL> parse(String data) throws Exception {
        List<URL> urls = new ArrayList<URL>();

        JSONObject object = JSONObject.parseObject(data);
        JSONArray dataArray = object.getJSONArray("data");

        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject obj = dataArray.getJSONObject(i);

            String imageUrl = obj.getString("objURL");
            if (imageUrl == null || imageUrl.isEmpty()) {
                continue;
            }
            urls.add(new URL(imageUrl));
        }

        return urls;
    }

    @Override
    protected URL buildSearchUrl(int pageIndex) {
        String baseUrl = engineInfo.getUrl();
        try {
            String url = baseUrl.replace(PAGE_INDEX, String.valueOf(pageIndex * engineInfo.getPageSize()))
                    .replace(PAGE_SIZE, String.valueOf(engineInfo.getPageSize()))
                    .replace(KEY_WORD, searchConditionInfo.getWord())
                    .replace(IMAGE_SIZE, searchConditionInfo.getImageSizeCode())
                    .replace(WIDTH, String.valueOf(searchConditionInfo.getWidth()))
                    .replace(HEIGHT, String.valueOf(searchConditionInfo.getHeight()));

            return new URL(url);
        }
        catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return null;
    }// @formatter:on

}
